package com.pet.system.controller;


import com.pet.system.common.AjaxResult;
import com.pet.system.entity.LoginUser;
import com.pet.system.entity.User;
import com.pet.system.service.TokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/system/token")
@Api(value = "TOKEN")
public class TokenController {
    @Autowired
    private TokenService tokenService;

    @PostMapping("/login")
    @ApiOperation("登录")
    public AjaxResult login(@RequestBody LoginUser loginUser) throws Exception {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = tokenService.login(loginUser);
        ajax.put("token", token);
        return ajax;
    }
    @ApiOperation("个人信息")
    @GetMapping("/getUserInfo")
    public AjaxResult getUserInfo(HttpServletRequest request) throws Exception {
        //从请求头内获取token
        String token = request.getHeader("authorization");
        User user = tokenService.getUser(token);
        return AjaxResult.success(user);
    }
    @ApiOperation("登出")
    @PostMapping("/logout")
    public AjaxResult logout(HttpServletRequest request) throws Exception {
        String token = request.getHeader("authorization");
        // 删除令牌
        tokenService.deleteLoginCacheToken(token);
        return AjaxResult.success();
    }
}
